#! /bin/bash

# 配置ElasticSearch
function configElasticSearch()
{

# 获取es安装文件
es_config=$1
# 获取主节点信息
master=$2
master_ip=`sudo cat /home/hadoop/automaticDeploy/host_ip.txt | grep node01 | cut -d " " -f1`

# 当前节点hostname
node=`hostname`
# 当前节点IP
host_ip=$(hostname --all-ip-addresses | awk '{print $1}')

cat >> $es_config <<EOF
cluster.name: es-cluster
node.name: ${node}
path.data: /var/elasticsearch/data
path.logs: /var/elasticsearch/log
network.host: ${host_ip}  
http.port: 9200 
discovery.seed_hosts: ["${master_ip}"] 
cluster.initial_master_nodes: ["${master}"]
node.master: true
node.data: true
node.ingest: true
EOF
}

function installES()
{
 #1.在frames.txt中查看是否需要安装es
 esInfo=`egrep "elasticsearch" /home/hadoop/automaticDeploy/frames.txt`
 
 es=`echo $esInfo | cut -d " " -f1`
 isInstall=`echo $esInfo | cut -d " " -f2`
 installNode=`echo $esInfo | cut -d " " -f3`
 master_node=`echo $esInfo | cut -d " " -f4`
 node=`hostname`
 
 #是否安装
 if [[ $isInstall = "true" && $installNode =~ $node ]];then
    
    #2.查看/opt/frames目录下是否有flume安装包
    esIsExists=`find /opt/frames -name $es`
    if [[ ${#esIsExists} -ne 0 ]];then
        if [[ ! -d /opt/app ]];then
            mkdir /opt/app && chmod -R 775 /opt/app
        fi
   
        #删除旧的
        es_home_old=`find /opt/app -maxdepth 1 -name "*elasticsearch*"`
        for i in $click_home_old;do
            rm -rf $i
        done

        #3.解压到指定文件夹/opt/app中
        echo "开始解压elasticsearch安装包"
        
        tar -zxvf $esIsExists -C /opt/app >& /dev/null
        echo "elasticsearch安装包解压完毕"

        es_home=`find /opt/app -maxdepth 1 -name "*elasticsearch*"`

        # 完成es参数配置
        configElasticSearch $es_home/config/elasticsearch.yml $master_node

        #4.配置FLUME_HOME
        profile=/etc/profile
        sed -i "/^export ES_HOME/d" $profile
        echo "export ES_HOME=$es_home" >> $profile

        #5.配置PATH
        sed -i "/^export PATH=\$PATH:\$ES_HOME\/bin/d" $profile
        echo "export PATH=\$PATH:\$ES_HOME/bin:" >> $profile

        #6.更新/etc/profile文件
        source /etc/profile && source /etc/profile
    else
        echo "/opt/frames目录下没有ES安装包"
    fi
 else
     echo "ES不允许被安装在当前节点"
 fi

}

# 待实现
function batchInstallES()
{
     #1.在frames.txt中查看是否需要安装es
    esInfo=`egrep "elasticsearch" /home/hadoop/automaticDeploy/frames.txt`
    
    isInstall=`echo $esInfo | cut -d " " -f2`
    installNode=`echo $esInfo | cut -d " " -f3`
    node=`hostname`

    #遍历配置ES服务节点
    OLD_IFS="$IFS" #保存旧的分隔符
    IFS=","
    nodes=($installNode)
    IFS="$OLD_IFS" # 将IFS恢复成原来的
    for i in "${!nodes[@]}"; do
        # 批量SSH执行
    done
    
}

installES
